<script setup>
import { ref, reactive, onMounted } from "vue";
import { useCartStore } from "@/stores/cart";
import { clearCartAPI,deleteCartAPI,getCartListAPI } from "@/apis/cart";
import { ElMessage, ElMessageBox } from 'element-plus';
import { createOrderAPI } from '@/apis/checkout';
import { useRouter } from 'vue-router';

const router = useRouter();
const cartStore = useCartStore();
onMounted(() => {
  updateCartDisplay();
})

const cartList = ref([]);

const count = ref(0);
const checked = ref(false);
const tableRef = ref();
const selected = reactive({
  selectNum: 0,
  cartTotalPrice: 0,
  selectList: [],
});

const handleSelectAll = (bool) => {
  if (bool) {
    // 勾选所有商品
    tableRef.value.toggleAllSelection();
  } else {
    // 清空所有选中商品
    tableRef.value.clearSelection();
  }
};


const handleSelecti = (selectedRows) => {
  selected.selectNum = selectedRows.reduce((total, row) => total + row.quantity, 0);
  selected.cartTotalPrice = selectedRows.reduce((total, row) => total + row.productTotalPrice, 0);
  selected.selectList = selectedRows;
  checked.value = selectedRows.length === cartList.value.length; // 动态判断全选状态
};


// 实现增减逻辑
const incrementCount = (cartId) => {
  const item = cartList.value.find(item => item.cartId === cartId);
  if (item) {
    item.quantity++;
    item.productTotalPrice = parseFloat((item.quantity * item.productUnitPrice).toFixed(2));
    // 如果当前列被选中，则更新选中数量和金额
    if (selected.selectList.includes(item)) {
      selected.selectNum++;
      selected.cartTotalPrice += item.productUnitPrice;
    }
  }
};

const decrementCount = (cartId) => {
  const item = cartList.value.find(item => item.cartId === cartId);
  if (item && item.quantity > 1) {
    item.quantity--;
    item.productTotalPrice = parseFloat((item.quantity * item.productUnitPrice).toFixed(2));

    // 如果当前列被选中，则更新选中数量和金额
    if (selected.selectList.includes(item)) {
      selected.selectNum--;
      selected.cartTotalPrice -= item.productUnitPrice;
    }
  }
};
/**
* 从购物车中删除指定ID的商品
* @param {number} itemId - 要删除的商品行ID
*/
async function deleteFromCart(cartId) {
  if (!cartId) {
    ElMessage.error('无法获取购物车 ID！');
    return;
  }

  const confirmDelete = await ElMessageBox.confirm("确定要删除该商品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });

  if (!confirmDelete) {
    return;
  }

  const index = cartList.value.findIndex(item => item.cartId === cartId);
  if (index !== -1) {
    cartList.value.splice(index, 1);
  }

  try {
    await deleteCartAPI(cartId);
    ElMessage.success("删除成功");
    updateCartDisplay();
  } catch (error) {
    ElMessage.error("删除失败");
    console.error("删除失败:", error);
  }
}



const updateCartDisplay = () => {
  getCartListAPI().then(res => {
    if (res.message === "购物车为空") {
      return;
    }

    cartStore.setCartInfo(res.data);
    const cartInfo = cartStore.cartInfo;

    cartList.value = cartInfo.cartList; // 获取购物车列表
    selected.selectNum = 0; // 初始化选中数量
    selected.cartTotalPrice = 0; // 初始化总价
    selected.selectList = []; // 初始化选中列表
    count.value = cartInfo.cartList.length;

    // 取消全选状态
    checked.value = false;
  });
};


/**
 * 处理结算购物车
 */
const handleCheckout = async () => {
  // 检查购物车是否为空
  if (cartList.value.length === 0) {
    ElMessage.warning('购物车为空，无法结算！');
    return;
  }

  // 检查是否有选中的商品
  if (selected.selectList.length === 0) {
    ElMessage.warning('请先选择商品进行结算！');
    return;
  }

  // 构造选中商品的结算信息
  const products = selected.selectList.map(item => ({
    productId: item.productId,
    productNum: item.quantity,
  }));

  try {
    // 调用创建订单的 API
    const res = await createOrderAPI(products);
    ElMessage.success('订单创建成功！');

    // 删除购物车中选中的商品
    for (const item of selected.selectList) {
      const cartId = item.cartId;
      const index = cartList.value.findIndex(cartItem => cartItem.cartId === cartId);
      if (index !== -1) {
        cartList.value.splice(index, 1); // 本地删除
        await deleteCartAPI(cartId); // 同步服务端删除
      }
    }

    // 重置选中状态
    selected.selectNum = 0;
    selected.cartTotalPrice = 0;
    selected.selectList = [];
    checked.value = false;

    // 更新购物车显示状态
    updateCartDisplay();

    // 跳转到订单确认页面
    router.push('/checkout/' + res.data);
  } catch (error) {
    ElMessage.error('创建订单失败');
    console.error('创建订单失败:', error);
  }
};


const handleClearCart = async () => {
  // 检查购物车是否为空
  if (cartList.value.length === 0) {
    ElMessage.warning('购物车为空，无需清空！');
    return;
  }

  // 弹出提示框，询问用户是否确认清空
  const confirmClear = await ElMessageBox.confirm("确定要清空购物车吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  });

  if (!confirmClear) {
    // 用户取消清空操作
    return;
  }

  // 清空购物车
  cartList.value = [];
      // cartStore.clearCart();
      selected.selectNum = 0;
      selected.cartTotalPrice = 0;
      selected.selectList = [];
      checked.value = false;
      count.value = 0;
      clearCartAPI().then(
        res => {
        }
      ).catch(error => {
        console.error('清空购物车失败:', error);
      });
  // 更新购物车的显示状态
  updateCartDisplay();
}

</script>


<template>
  <div class="container">
    <div class="cart">
      <el-row class="cart-filter-bar">
        <h3>购物车（全部{{ count }}）</h3>
      </el-row>
      <el-row class="cart-list">
        <el-table :data="cartList" ref="tableRef" style="width: 100%" @selection-change="handleSelecti"><el-table-column
            type="selection" width="55"></el-table-column>
          <el-table-column prop="productName" label="商品信息" width="400"></el-table-column>
          <el-table-column prop="productUnitPrice" label="单价" width="180"></el-table-column>
          <el-table-column prop="quantity" label="数量" width="180">
            <template #default="{ row }">
              <button @click="decrementCount(row.cartId)">-</button>
              <span style="margin: 0 1rem;">{{ row.quantity }}</span>
              <button @click="incrementCount(row.cartId)">+</button>
            </template>
          </el-table-column>
          <el-table-column prop="productTotalPrice" label="金额" width="180"></el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="deleteFromCart(row.cartId)">删除</el-button>
            </template>
          </el-table-column>
          <template #empty>
            <div class="cart-none">
                  <el-empty description="购物车列表为空">
                    <el-button type="primary" @click="$router.push('/')">随便逛逛</el-button>
                  </el-empty>
                </div>
          </template>
        </el-table>
      </el-row>

      <div class="float-bar">
        <div class="selectAll">
          <el-checkbox v-model="checked" @change="handleSelectAll(selected.selectList)">全选</el-checkbox>
        </div>
        <div class="total">
          <span>已选商品</span>
          <span>{{ selected.selectNum }}</span>
          <span>件</span>
          <span>合计（不含运费）：</span>
          <span>￥</span>
          <span>{{ selected.cartTotalPrice.toFixed(2) }}</span>
          <el-button class="toSettle" type="primary" size="large" @click="handleCheckout">结算</el-button>
          <el-button @click="handleClearCart" size="large">清空</el-button>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped lang="scss">
.cart {
  border-radius: 1.5rem;
  border: 1px solid #aaa;
  margin-top: 2rem;
  overflow: hidden;
  background-color: #ffffff;

  .cart-filter-bar {
    height: 6rem;
    line-height: 6rem;
    border-bottom: #aaa solid 1px;

    h3 {
      margin-left: 1.5rem;
      font-size: 1.5rem;
      font-weight: bold;
    }
  }

  .cart-list {
    min-height: 10rem;

    /**设置第一个不显示**/
    .cell:first-child {
      display: none;
    }
    .cart-none {
    text-align: center;
    padding: 120px 0;
    background: #fff;

    p {
      color: #999;
      padding: 20px 0;
    }
  }
  }

  .float-bar {
    height: 6rem;
    line-height: 6rem;
    border-top: #aaa solid 1px;
    background-color: #fafafa;

    .selectAll {
      float: left;
      margin-left: 1.5rem;
      font-size: 1.2rem;

      a {
        margin-left: 1rem;
      }
    }

    .total {
      float: right;
      margin-right: 1.5rem;
      font-size: 1.2rem;

      span {
        margin-left: 1rem;
      }

      .toSettle {
        margin-left: 1rem;
      }
    }
  }
}
</style>
